package com.example.java_chatroom.controller;

import com.example.java_chatroom.component.OnlineUserManager;
import com.example.java_chatroom.constant.Constants;
import com.example.java_chatroom.model.*;
import com.example.java_chatroom.service.MessageService;
import com.example.java_chatroom.service.MessageSessionService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class WebSocketController extends TextWebSocketHandler {

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MessageSessionService messageSessionService;

    @Autowired
    private MessageService messageService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("[WebSocketController]建立连接成功");
        UserInfo userInfo = (UserInfo) session.getAttributes().get(Constants.USER_SESSION);
        if(userInfo==null){
            return;
        }
        log.info("获取userId:"+userInfo.getUserId());
        //将映射关系存储起来
        onlineUserManager.online(userInfo.getUserId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("[WebSocketController]接收消息："+message.toString());
        //1.先获取登录用户的信息
        UserInfo userInfo=(UserInfo) session.getAttributes().get(Constants.USER_SESSION);
        if(userInfo == null){
            log.info("[WebSocket 获取用户失败]，不能转发消息");
        }
        //2.获取要转发的消息
        //根据协议，req是JSON类型，我们要转换为MessageRequest类型
        MessageRequest messageRequest=objectMapper.readValue(message.getPayload(),MessageRequest.class);
        //判断消息类型
        if(messageRequest.getType().equals("message")){
            transferMessage(userInfo,messageRequest);
        }else {
            log.info("[WebSocket 消息类型错误]"+message.getPayload());
        }
    }

    //该方法完成转发消息的逻辑
    //fromUser表示消息从哪个用户发来的
    private void transferMessage(UserInfo fromUser, MessageRequest messageRequest) throws IOException {
        //1.构造一个响应对象
        MessageResponse response=new MessageResponse();
        response.setFromId(fromUser.getUserId());
        response.setFromName(fromUser.getUsername());
        response.setSessionId(messageRequest.getSessionId());
        response.setContent(messageRequest.getContent());
        //将Java对象转为JSON对象
        String respJSON=objectMapper.writeValueAsString(response);
        log.info("转发的消息respJSON："+respJSON);
        //2.根据sessionId获取对应的会话中有哪些对象
        List<Friend> friends=messageSessionService.getFriendsBySessionId(messageRequest.getSessionId(), fromUser.getUserId());
        //上述从数据库中查询的friends已经排除了用户自己
        //但是我们需要将发送的消息给自己也转发一份，则需要将自己添加进去
        Friend myself=new Friend();
        myself.setFriendId(fromUser.getUserId());
        myself.setFriendName(fromUser.getUsername());
        friends.add(myself);
        //3.遍历friends，将消息转发给friend
        for(Friend friend:friends){
            WebSocketSession session= onlineUserManager.getSession(friend.getFriendId());
            if(session == null){
                log.info("该用户不在线");
                //用户不在线，消息不发送
                continue;
            }
            //不能直接将respJSON转发，要封装
            session.sendMessage(new TextMessage(respJSON));
        }
        //4.将转发的消息插入到数据库表中，方便后面用户上线能接受到消息
        //首先得创造一个Message对象
        Message message=new Message();
        message.setFromId(fromUser.getUserId());
        message.setFromName(fromUser.getUsername());
        message.setSessionId(messageRequest.getSessionId());
        message.setContent(messageRequest.getContent());
        messageService.add(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("[WebSocketController]连接出现异常");
        UserInfo userInfo=(UserInfo) session.getAttributes().get(Constants.USER_SESSION);
        if(userInfo==null){
            return;
        }
        onlineUserManager.offline(userInfo.getUserId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("[WebSocketController]连接关闭,"+status.toString());
        UserInfo userInfo=(UserInfo) session.getAttributes().get(Constants.USER_SESSION);
        if(userInfo==null){
            return;
        }
        onlineUserManager.offline(userInfo.getUserId(),session);
    }
}
